const browserSync = require('browser-sync').create()
const reload = browserSync.reload
const nodemon = require('gulp-nodemon')
const gulp = require('gulp')

//资源文件跨域配置
const cors = function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*')
  next()
}

gulp.task('node', function() {
  nodemon({
    script: './app',
    ext: 'js html',
    env: {
      NODE_ENV: 'development'
    }
  })
})

gulp.task('js', function() {
  return gulp
    .src('public/js/*js')
    .pipe(browserify())
    .pipe(uglify())
    .pipe(gulp.dest('dist/js'))
})

gulp.task('js-watch', ['js'], function(done) {
  browserSync.reload()
  done()
})

gulp.task('default', ['js'], function() {
  browserSync.init({
    server: {
      baseDir: './'
    }
  })

  gulp.watch('public/js/*js', ['js-watch'])
})

// gulp.task('localhostServer', function() {
//   localhostServer.server({
//     port: 443,
//     https,
//     host: '',
//     livereload: true,
//     middleware: function() {
//       return [cors]
//     }
//   })
// })

gulp.task('server', ['node'], function() {
  const files = ['views/*.ejs', 'public/**/*.*']

  browserSync.init(files, {
    browser: 'chrome',
    proxy: 'http://localhost:5501',
    changeOrigin: true,
    notify: false,
    port: 5500
  })

  gulp.watch(files).on('change', reload)
})
